"""
The MIT License (MIT)
Copyright © 2020 Walkline Wang (https://walkline.wang)
https://gitee.com/walkline/MicroPython-with-Aligenie-Voice-Skill
"""
from utime import sleep_ms
from MicroWebSrv2 import *
from webserver import WebServer
from config import Config
from aligenie.aligenie import Aligenie


RETURN_DATA = {
    "returnCode": "0",
    "returnErrorSolution": "",
    "returnMessage": "",
    "returnValue": {
        "reply": "",
        "resultType": "RESULT",
        "executeCode": "SUCCESS",
        "msgInfo": ""
    }
}

web_server = None

"""
WebRoute
"""
@WebRoute(GET, '/')
def homepage(microWebSrv2, request):
	request.Response.ContentType = "text/html"
	request.Response.ContentCharset = "UTF-8"
	request.Response.ReturnOk('<h1>Aligenie Service Running...</h1>')

# @WebRoute(GET, '/aligenie/ae355cb2dbb210bd4c2debcbe7b5f903.txt')
# def authorize(microWebSrv2, request, args={}):
# 	try:
# 		# with open(args['authfile']) as file:
# 		with open("ae355cb2dbb210bd4c2debcbe7b5f903.txt") as file:
# 			auth_code = file.readline()
# 	except OSError as ose:
# 		if str(ose) == "[Errno 2] ENOENT":
# 			print("Cannot found authorize file...")
# 			request.Response.ReturnNotFound()

# 	request.Response.ReturnOk(auth_code)

@WebRoute(POST, '/skill')
def skill(microWebSrv2, request):
	aligenie = Aligenie(request.GetPostedJSONObject())

	if aligenie.skill_name == Config.SKILL_NAME:
		if aligenie.intent_name == Config.SKILL_INTENT_WEATHER:
			RETURN_DATA['returnValue']['reply'] = "查询内容：天气；查询城市：{} ；查询日期：{}".format(aligenie.city, aligenie.date)
	else:
		RETURN_DATA['returnValue']['reply'] = "技能不存在，或暂时无法查询！"

	request.Response.ReturnOkJSON(obj=RETURN_DATA)




def start_web_server():
	web_server = WebServer(root_path=Config.SERVER_ROOT, port=Config.SERVER_PORT)
	web_server.start()

	while web_server.is_running():
		sleep_ms(100)


if __name__ == "__main__":
	try:
		start_web_server()
	except KeyboardInterrupt:
		print("\nPRESS CTRL+D TO RESET DEVICE")

		if web_server is not None:
			web_server.stop()
